
import 'dart:async';
import 'dart:io';

import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/common/ui/val_loader_toast.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

import '../../http/val_dio_fetch_kit.dart';
import '../config/val_client_url_path.dart';
class ValApplePayTool {

  final bool _kAutoConsume = Platform.isIOS || true;

  ValApplePayTool._inner();

  static final ValApplePayTool _i = ValApplePayTool._inner();

  factory ValApplePayTool() => _i;

  static const String _kConsumableId = 'consumable';
  static const String _kUpgradeId = 'upgrade';
  static const String _kSilverSubscriptionId = 'subscription_silver';
  static const String _kGoldSubscriptionId = 'subscription_gold';
  List<ProductDetails> _products = <ProductDetails>[];
  late StreamSubscription<List<PurchaseDetails>> _subscription;

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  static final List<String> _kProductIds = <String>[
    _kConsumableId,
    _kUpgradeId,
    _kSilverSubscriptionId,
    _kGoldSubscriptionId,
  ];

  Future<void> init() async {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
          _listenToPurchaseUpdated(purchaseDetailsList);
          // CommonDialogImpl.hideProgress();
        }, onDone: () {
          _subscription.cancel();
        }, onError: (Object error) {
          // handle error here.
          ValUIKitDialogImpl.hideProgress();
        });

    var transactions = await SKPaymentQueueWrapper().transactions();
    transactions.forEach((skPaymentTransactionWrapper) {
      SKPaymentQueueWrapper().finishTransaction(skPaymentTransactionWrapper);
    });
  }

  Callback? completionBlock;
  String orderNo = '';
  Future<void> applePay(Map dataMap, Callback completion) async {
    completionBlock = completion;
    /// _inAppPurchase是否有效
    final bool isAvailable = await _inAppPurchase.isAvailable();
    if (!isAvailable) {
      return;
    }
    /// 如果是iOS设备进行设置代理，接口苹果服务器的回调。
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
      _inAppPurchase
          .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
    }

    /// 获取后台返回的产品id
    if (dataMap['goodsCode'] == null) {
      ValLoaderToast.show('No products yet');
      return;
    }
    _kProductIds.add(dataMap['goodsCode']);

    /// 查询后台返回的ProductId是否在苹果服务器上注册了
    final ProductDetailsResponse productDetailResponse =
    await _inAppPurchase.queryProductDetails(_kProductIds.toSet());
    /// 查询不到说明没注册
    if (productDetailResponse.error != null) {
      ValLoaderToast.show('Failed to obtain product information');
      return;
    }
    /// 查询不到商品详情说明没注册
    if (productDetailResponse.productDetails.isEmpty) {
      ValLoaderToast.show('No products yet');
      return;
    }
    orderNo = dataMap['orderNo'];
    _products = productDetailResponse.productDetails;
    /// 查询成功
    ProductDetails productDetails = _products[0];
    // FlutterKeychain.put(key: "iosPrice", value: productDetails.price);
    late PurchaseParam purchaseParam;
    purchaseParam = PurchaseParam(
        productDetails: productDetails,

        /// 添加自己服务器上生成的订单
        applicationUserName:
        '${dataMap['orderNo']}');
    /// 向苹果服务器发起支付请求
    _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
    var transactions = await SKPaymentQueueWrapper().transactions();
    transactions.forEach((skPaymentTransactionWrapper) {
      SKPaymentQueueWrapper().finishTransaction(skPaymentTransactionWrapper);
    });
    print('==========开始支付==========');
  }

  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    print('==========xxxxxx==========');
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        /// 等待购买中
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        /// 取消订单
        _inAppPurchase.completePurchase(purchaseDetails);
        ValUIKitDialogImpl.hideProgress();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          /// 购买出错
          ValLoaderToast.show('Purchase error');
          _inAppPurchase.completePurchase(purchaseDetails);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          print('==========支付成功==========');
          print('==========${purchaseDetails.verificationData.serverVerificationData}==========');
          print('==========${purchaseDetails.purchaseID ?? ''}==========');
          print('==========支付成功==========');
          /// 调用后台接口,发放商品
          payment(orderNo,
              purchaseDetails.verificationData.serverVerificationData,
              purchaseDetails.purchaseID ?? '', (p0) => {

              });
          // deliverProduct(purchaseDetails);
        }
      }
    }
  }

  /// 生成商品订单
  void createOrder(String goodsCode , Function (dynamic) completion) {
    ValUIKitDialogImpl.showProgress();
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.createApplyPayOrder,
        { 'entry' : '' ,
          'goodsCode' : goodsCode,
          'payChannel' : 'IAP',
          'source' : ''
        }, (data, errorCode, message) {
          if (errorCode == 0) {
            completion(data);

          } else {
            ValUIKitDialogImpl.showNetErr('Failed to generate order');
          }
        },  (err)  {
          ValUIKitDialogImpl.showNetErr('Failed to generate order');
        });
  }

  /// 验证苹果支付
  void payment(String orderNo ,
      dynamic playload ,
      dynamic transactioId ,
      Function (dynamic) completion) {
    ValUIKitDialogImpl.showProgress();
    print('验证支付=====');
    print('验证支付${orderNo}=====');
    print('验证支付$playload=====');
    print('验证支付$transactioId=====');
    print('验证支付=====');
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.createApplyPayment,
        { 'orderNo' : orderNo ,
          'payload' : playload,
          'transactionId' : transactioId,
          'type' : '1'
        }, (data, errorCode, message) {
          ValUIKitDialogImpl.hideProgress();
          print('========');
          print('====$data====');
          print('====$errorCode====');
          print('====$message====');
          if (errorCode == 0) {
            completion(data);
            completionBlock?.call();
            print('支付验证成功');
          } else {
            ValUIKitDialogImpl.showNetErr('Failed to generate order');
          }
        },  (err)  {
          ValUIKitDialogImpl.hideProgress();
          ValUIKitDialogImpl.showNetErr('Failed to generate order');
        });
  }
}

class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}